package tool

import (
	"fmt"

	"log"
	"net/http"
	"strings"
)

func Http(method, url, params string, header *map[string]string) *http.Response {
	i := 0
	var resp *http.Response
	for i = 0; i < 5; i++ {
		client := &http.Client{}
		req, err := http.NewRequest(method, url, strings.NewReader(params))
		if err != nil {
			log.Fatal("new request error: ", err)
			return nil
		}
		for k, v := range *header {
			req.Header.Add(k, v)
		}
		resp, err = client.Do(req)
		if err != nil {
			log.Fatal("get response error: ", err)
			return nil
		}
		if resp.StatusCode == 200 {
			break
		}
	}
	return resp
}

func Login(url string) string {
	header := &map[string]string{}
	resp := Http("GET", url, "", header)
	cookieStr := ""
	for _, v := range resp.Cookies() {
		cookieStr += fmt.Sprintf("%s=%s;", v.Name, v.Value)
	}
	// fmt.Println("resp: ", resp)
	return cookieStr
}
